import React, { useState, useEffect } from 'react';
import './pay.css';
import * as XLSX from 'xlsx';
import { getPay } from '../../../request/api';
import { Button, Table } from 'antd';
import { Select, Space, Modal, Form, Radio } from 'antd';
import { Input } from 'antd';
import { DatePicker } from 'antd';
import type { TableProps } from 'antd';
const { TextArea } = Input;


interface DataType {
    id: number;
    name: string;
    title: string;
    phone: string;
    yewu: string;
    liushui: string;
    time: string;
    qian: number;
    dian: string;
}

function Pay() {
    const [table, setTable] = useState<DataType[]>([]); // 设置为 DataType 数组
    const [businessType, setBusinessType] = useState<string | undefined>();
    const [storeName, setStoreName] = useState<string>('');
    const [phoneNumber, setPhoneNumber] = useState<string>('');
    const [dateRange, setDateRange] = useState<moment.Moment[]>([]); // 改为 moment 类型
    // 用于管理弹窗的状态
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isModalOpen, setIsModalOpen] = useState(false);
    const [formValues, setFormValues] = useState<DataType | null>(null)
    useEffect(() => {
        fetchTableData();
    }, []);

    const fetchTableData = () => {
        getPay().then(res => {
            // console.log(res, '000');
            setTable(res.data.list || []);
        });
    }

    const handleQuery = () => {
        // 多环境搜索
        const filteredTable = table.filter(item => {
            const isBusinessTypeMatch = businessType ? item.yewu === businessType : true;
            const isStoreNameMatch = storeName ? item.title.includes(storeName) : true;
            const isPhoneNumberMatch = phoneNumber ? item.phone.includes(phoneNumber) : true;

            const isDateMatch = dateRange.length === 2
            ? moment(item.time).isBetween(dateRange[0], dateRange[1], null, '[]')
            : true;

            return isBusinessTypeMatch && isStoreNameMatch && isPhoneNumberMatch && isDateMatch;
        });

        setTable(filteredTable);
    };

    const columns: TableProps<DataType>['columns'] = [
        {
            title: '序号',
            dataIndex: 'id',
            key: 'id',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '用户名',
            dataIndex: 'name',
            key: 'name',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '店铺名称',
            dataIndex: 'title',
            key: 'title',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '手机号',
            dataIndex: 'phone',
            key: 'phone',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '业务单据',
            dataIndex: 'dan',
            key: 'dan',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '业务类型',
            dataIndex: 'yewu',
            key: 'yewu',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '流水类型',
            dataIndex: 'liushui',
            key: 'liushui',
            render: (text) => <a>{text}</a>,
        },
        {
            title: '果币(元)',
            dataIndex: 'qian',
            key: 'qian',
        }
    ];

    // 导出到 Excel 的函数
    const exportToExcel = () => {
        const ws = XLSX.utils.json_to_sheet(table);  // 将数据转换为工作表
        const wb = XLSX.utils.book_new(); // 创建新的工作簿
        XLSX.utils.book_append_sheet(wb, ws, 'Sheet1'); // 将工作表添加到工作簿
        XLSX.writeFile(wb, 'data.xlsx'); // 导出文件
    };
    const handleChange = (value: string) => {
        console.log(`selected ${value}`);
    };
    

    const { RangePicker } = DatePicker;

    const [title, setTitle] = useState('')
    // 弹窗
    const showAddModal = () => {
        setTitle('新增')
        setIsModalVisible(true);
        setFormValues(null); // 清空表单
    };

    const handleModalOk = (values: DataType) => {
        const newEntry = { id: table.length + 1, ...values };
        setTable([...table, newEntry]); // 添加新数据
        setIsModalVisible(false); // 关闭弹窗
    };

    const handleModalCancel = () => {
        setIsModalVisible(false);
        setIsModalOpen(false)
    };
    // 充值弹窗
    const payModal = () => {
        setTitle('充值')
        setIsModalOpen(true)
    }

    const [value, setValue] = useState(1);

    const onChange = (e: RadioChangeEvent) => {
        console.log('radio checked', e.target.value);
        setValue(e.target.value);
    };

    return (
        <div className='pay_box'>
            <div className='pay_top'>
                <h3>果币</h3>
                <Select
                    defaultValue="业务类型"
                    style={{ width: 120, margin: '0 20px' }}
                    onChange={(value) => setBusinessType(value)}
                    options={[
                        { value: '充值', label: '充值' },
                        { value: '订单消费', label: '订单消费' },
                        { value: '退款', label: '退款' },
                    ]}
                />
                <span>店铺名称：</span>
                <Input
                    placeholder="Basic usage"
                    style={{ width: 220, marginRight: '20px' }}
                    value={storeName}
                    onChange={(e) => setStoreName(e.target.value)} />

                <span>手机号:</span>
                <Input
                    placeholder="Basic usage"
                    style={{ width: 220, marginRight: '20px' }}
                    value={phoneNumber}
                    onChange={(e) => setPhoneNumber(e.target.value)} />

                <div className='top_day'>
                    <span>日期查询:</span>
                    <DatePicker  onChange={(dates) => {
                            if (dates) {
                                setDateRange(dates);
                            } else {
                                setDateRange([]); // 重置状态
                            }
                        }} style={{ marginRight: '20px' }} />
                    <Button type="primary" onClick={handleQuery}>查询</Button>
                    <Button onClick={exportToExcel}>导出</Button>
                </div>
            </div>

            <div className='pay_tab'>
                <Button type='primary' onClick={showAddModal}>新增</Button>
                <Button type='primary' onClick={payModal}>充值</Button>

                <Table<DataType> columns={columns} dataSource={table} />

                <Modal
                    title={title}
                    visible={isModalVisible}
                    onCancel={handleModalCancel}
                    footer={null}
                >
                    <Form
                        onFinish={handleModalOk}
                        layout="vertical"
                    >
                        <Form.Item
                            label="用户名"
                            name="name"
                            rules={[{ required: true, message: '请输入用户名' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="店铺名称"
                            name="title"
                            rules={[{ required: true, message: '请输入店铺名称' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="手机号"
                            name="phone"
                            rules={[{ required: true, message: '请输入手机号' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="业务类型"
                            name="yewu"
                            rules={[{ required: true, message: '请输入业务类型' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="流水类型"
                            name="liushui"
                            rules={[{ required: true, message: '请输入流水类型' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item
                            label="果币(元)"
                            name="qian"
                            rules={[{ required: true, message: '请输入果币' }]}
                        >
                            <Input />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit">添加</Button>
                        </Form.Item>
                    </Form>
                </Modal>


                <Modal
                    title={title}
                    visible={isModalOpen}
                    onCancel={handleModalCancel}
                    footer={null}
                >
                    <div>
                        <span>充值类型</span>
                        <Radio.Group onChange={onChange} value={value}>
                            <Radio value={1}>平台果币</Radio>
                            <Radio value={2}>店铺果币</Radio>

                        </Radio.Group>
                    </div>

                    <div>
                        <span>手机号</span>
                        <TextArea rows={4} />
                    </div>

                    <div>
                        <span>充值金额</span>
                        <Input style={{ width: 100 }} />元
                    </div>
                    <div>
                        <span>赠送金额</span>
                        <Input style={{ width: 100 }}/>元
                    </div>
                    <div>
                        <span>管理员密码</span>
                        <Input style={{ width: 100 }}/>
                    </div>
                    <div>
                        <Button type="primary" >确定充值</Button>
                        <Button >取消</Button>
                    </div>
                </Modal>
            </div>

        </div>
    );
}

export default Pay;